package com.adnaan.backend.service.impl;

import com.adnaan.backend.entity.Medicinal;
import com.adnaan.backend.entity.Pictures;
import com.adnaan.backend.entity.dto.OptionDto;
import com.adnaan.backend.entity.dto.PictureListDto;
import com.adnaan.backend.entity.vo.EfficacyVo;
import com.adnaan.backend.entity.vo.PicturesVo;
import com.adnaan.backend.mapper.MedicinalMapper;
import com.adnaan.backend.service.MedicinalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * author: adnaan
 * create: 2025-02-03 13:50
 * Description:
 */
@Service
public class MedicinalServiceImpl extends ServiceImpl<MedicinalMapper, Medicinal> implements MedicinalService {
    @Override
    public List<OptionDto> getEfficacy(Long id) {
        return baseMapper.getEfficacy(id);
    }

    @Override
    public boolean deleteEfficacy(Long id, Long efficacyId) {
        return baseMapper.deleteEfficacy(id, efficacyId);
    }

    @Override
    public void deleteAllEfficacy(Long materialId) {
        baseMapper.deleteAllEfficacy(materialId);
    }

    @Override
    public boolean updateEfficacy(EfficacyVo efficacyVo) {
        // 删除药材所有的功效
        deleteAllEfficacy(efficacyVo.getMaterialId());
        // 新增药材的功效
        if (efficacyVo.getEfficacyIds() != null && !efficacyVo.getEfficacyIds().isEmpty()) {
            efficacyVo.getEfficacyIds().forEach(efficacyId -> {
                baseMapper.insertEfficacy(efficacyVo.getMaterialId(), efficacyId);
            });
        }
        return true;
    }

    @Override
    public String getDefaultPicture(Long id) {
        return baseMapper.getDefaultPicture(id);
    }

    @Override
    public boolean addPictures(PicturesVo picturesVo) {
        Long materialId = picturesVo.getMaterialId();
        List<String> pictures = picturesVo.getPictures();

        if (pictures == null || pictures.isEmpty()) {
            return false;
        }

        pictures.forEach(picture -> {
            // 插入图片并获取生成的 ID
            Pictures pictureRecord = new Pictures();
            pictureRecord.setImage(picture);
            pictureRecord.setHerbalId(materialId);
            baseMapper.insertPictures(pictureRecord); // 确保 keyProperty 映射到 id
        });

        return true;
    }

    @Override
    public List<PictureListDto> pictures(Long materialId) {
        return baseMapper.pictures(materialId);
    }

    @Override
    public boolean deletePicture(Long picId) {
        return baseMapper.deletePicture(picId);
    }

}
